{% extends 'web/system.html' %}
{% load static %}

{% block css %}
<link rel="stylesheet" href="{% static 'editView.css' %}">
{% endblock css %}

{% block content %}
<!-- 这里添加其他样式等等 -->

{% if mode == 'edit' %}
<div class="edit-space">
    <div class="toolbar">
        <span class="symbol">
            <span class="file-name"></span>
            <span class="type"><i style="float: right;">编辑</i></span>
        </span>
        <button id="read"><ion-icon name="book-outline"></ion-icon>浏览</button>
        <button id="back"><ion-icon name="return-down-back-outline"></ion-icon>后退</button>
        <button id="forward"><ion-icon name="return-down-forward-outline"></ion-icon>前进</button>
        <button id="save"><ion-icon name="save-outline"></ion-icon>保存</button>
        <span class="modify-time">上次修改时间 2014/5/4/8:50</span>
    </div>
    <textarea wrap="off" id="word-board" cols="100" rows="10" oninput="listenInput(this)"
        onkeydown="listenKeyDown(event)" onkeyup="listenKeyUp(event)">
    </textarea>
</div>
{% csrf_token %}
{% else %}
<div class="edit-space">
    <div class="toolbar">
        <span class="symbol">
            <span class="file-name"></span>
            <span class="type"><i style="float: right;">只读</i></span>
        </span>
        {% if condition == 'home' %}
        <button id="edit"><ion-icon name="create-outline"></ion-icon>编辑</button>
        {% else %}
        <button style="cursor: not-allowed;"><ion-icon name="create-outline"></ion-icon>编辑</button>
        {% endif %}
        <span class="modify-time">上次修改时间 2014/5/4/8:50</span>
    </div>
    <textarea wrap="off" id="word-board" cols="100" rows="10" readonly></textarea>
</div>
{% endif %}
{% endblock content %}
{% block script %}
<script>
    $.ajax({
        url: "{% url 'editContent' condition %}",
        type: 'GET',
        data: {
            ID: '{{ ID }}'
        },
        success: (res) => {
            // 加载
            document.querySelector('.file-name').innerHTML = res['file_name']
            document.querySelector('.modify-time').innerHTML = '<b>上次修改时间: </b>' + res['m_time']
            document.querySelector('#word-board').value = res.content
        },
        async: false
    })
</script>
{% if mode == 'edit' %}
<script>
    // edit
    $('#read').click(() => {
        window.location.href = "{% url 'editView' condition 'read' ID %}"
    })
    let pointer = -1
    const cache = []
    const MAX_LEN = 50
    const wordBoard = document.querySelector('#word-board')

    // 初始化最初值
    cache.push(wordBoard.value)
    pointer += 1

    function listenInput (node) {
        // 当开始输入，意味着pointer之后的缓存丢失
        while ((pointer + 1) < cache.length) {
            cache.pop()
        }
        // 当缓存达到上限，丢失最先更改记录
        if (cache.length >= MAX_LEN) {
            cache.shift()
            pointer -= 1
        }
        // 压入值
        cache.push(node.value)
        pointer += 1
    }

    // 处理tab建
    let shift = false
    function listenKeyDown (e) {
        if (event.keyCode == 9) { //tab was pressed
            let start = wordBoard.selectionStart
            let end = wordBoard.selectionEnd
            const value = wordBoard.value
            if (!shift) {
                // forward
                wordBoard.value = value.substring(0,
                    start) + ' '.repeat(4) + value.substring(end,
                        value.length)
                wordBoard.selectionEnd = start + 4
            } else {
                // back
                const lines = value.split('\n')
                line = lines[lines.length - 1]
                if (line.substring(0, 4) === '    ') {
                    line = line.substring(4, line.length)
                    lines[lines.length - 1] = line
                    wordBoard.value = lines.join('\n')
                    wordBoard.selectionStart = start - 4
                    wordBoard.selectionEnd = end - 4
                }
            }
            listenInput(wordBoard)
            e.preventDefault()
        }
        if (event.keyCode == 16) {
            shift = true
            e.preventDefault()
        }
    }

    function listenKeyUp (e) {
        if (event.keyCode == 16) {
            shift = false
            e.preventDefault()
        }
    }

    $('#back').click(() => {
        pointer = pointer - 1 >= 0 ? pointer - 1 : 0
        wordBoard.value = cache[pointer]
    })
    $('#forward').click(() => {
        pointer = pointer + 1 >= cache.length ? cache.length - 1 : pointer + 1
        wordBoard.value = cache[pointer]
    })
    $('#save').click(() => {
        value = wordBoard.value
        $.ajax({
            url: "{% url 'editSave' condition %}",
            type: 'POST',
            data: {
                csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val(),
                content: value,
                ID: '{{ ID }}'
            },
            success: (res) => {
                alert('保存成功！')
                window.location.reload()
            }
        })
    })
</script>
{% else %}
<script>
    // read
    $('#edit').click(() => {
        window.location.href = "{% url 'editView' condition 'edit' ID %}"
    })
</script>
{% endif %}
{% endblock script %}